package com.bestcem.xm.survey.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.bestcem.xm.component.mybatis.service.impl.XmServiceImpl;
import com.bestcem.xm.componet.redis.service.RedisService;
import com.bestcem.xm.survey.entity.SurveyQuotaCheckItem;
import com.bestcem.xm.survey.mapper.SurveyQuotaCheckItemMapper;
import com.bestcem.xm.survey.service.SurveyQuotaCheckItemService;
import com.bestcem.xm.survey.util.SurveyConstant;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author guita
 * @description 针对表【ds_survey_quotacheckitem】的数据库操作Service实现
 * @createDate 2023-01-09 15:15:37
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class SurveyQuotaCheckItemServiceImpl extends XmServiceImpl<SurveyQuotaCheckItemMapper, SurveyQuotaCheckItem>
        implements SurveyQuotaCheckItemService {

    private @NonNull RedisService redisService;

    @Override
    public SurveyQuotaCheckItem quoteCountAutoInc(String check_items_id, Integer step) {
        SurveyQuotaCheckItem rspd_count = null;
        if (StrUtil.isBlankIfStr(check_items_id) || step == null) {
            return null;
        }
        //baseMapper.getByIdForUpdate(check_items_id);
        //select for update，改成redis实现
        String lockKey = String.format(SurveyConstant.QUOTE_COUNT_AUTO_INC_LOCK_FORMAT_KEY, check_items_id);
        //
        if (redisService.tryLock(lockKey, 1, TimeUnit.SECONDS)) {
            try {
                rspd_count = baseMapper.selectById(check_items_id);
                if (Objects.isNull(rspd_count)) {
                    log.error("quote_count_auto_inc check_items_id={} not exists", check_items_id);
                } else {
                    LambdaUpdateWrapper<SurveyQuotaCheckItem> updateWrapper = new LambdaUpdateWrapper<>();
                    SurveyQuotaCheckItem update = new SurveyQuotaCheckItem();
                    update.setId(check_items_id);
                    update.setCurCount(rspd_count.getCurCount() == null ? step : rspd_count.getCurCount() + step);
                    baseMapper.updateById(update);
                    
                    rspd_count.setCurCount(update.getCurCount());
                }
            } finally {
                redisService.unlock(lockKey);
            }
        } else {
            log.error("quote_count_auto_inc check_items_id={} tryLock faild", check_items_id);
        }
        return rspd_count;
    }
}




